/**
 * 管理后台 - 首页 - 顶部导航栏
 * Author: Zeon
 * Date: 2017/8/1
 * Created by Panxsoft.
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
.v-nav-header {
    position: relative;
    height: 60px;
    background: #fff;
	box-shadow: 0 1px 1px rgba(0,0,0,.1);

    .drop-down {
        margin: 20px 30px 0 0;
		float: right;
		&.lang {
			margin-top: 12px;
		}
    }

    .inline-middle {
        position: absolute;
        top: 0;
        bottom: 0;
        margin: auto 0;
    }

    /*面包屑样式布局*/
    .breadcrumb-area {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 60px;
        right: 200px;
        padding: 10px;
        line-height: 1;
    }

    .breadcrumb-middle {
        padding: 13px 0;
    }
    /*面包屑样式布局 END*/

    img {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 10%;
        margin: auto;
    }

    .badge {
        margin: 20px 30px 0 0;
        float: right;

        .notification {
            cursor: pointer;
        }
    }

     .ivu-btn-text:focus {
        box-shadow: none;
    }

}
</style>
<template>
	<div class="v-nav-header layout-header">

		<i-button
			:style="{transform: 'rotateZ(' + (shrink ? '-90' : '0') + 'deg)'}"
			type="text"
			class="inline-middle"
			name="collapsed__sider"
			@click="toggleClick()">
			<Icon
				type="navicon"
				size="32"/>
		</i-button>

		<div class="breadcrumb-area">
			<Breadcrumb class="breadcrumb-middle">
				<Breadcrumb-item
					v-for="breadcrumb in currentBreadcrumb"
					:to="breadcrumb.href"
					:key="breadcrumb.href">
					{{ breadcrumb.name }}
				</Breadcrumb-item>
			</Breadcrumb>
		</div>

		<Dropdown
			class="drop-down"
			trigger="click"
			placement="bottom-end"
			@on-click="clickDropdown">
			<a
				href="javascript:void(0)"
				name="welcome">
				{{ this.$t('template.welcome', {name: (getUserInfo.name || this.$t('template.admin')) }) }}
				<Icon type="arrow-down-b"/>
			</a>

			<Dropdown-menu slot="list">
				<Dropdown-item name="edit-user-info">
					<a
						name="user_info"
						href="javascript:void(0)">
						{{ $t('template.user_info') }}
					</a>
				</Dropdown-item>
				<!-- <Dropdown-item
					v-if="Number(getUserInfo.has_youzan) === 1"
					name="youzan">
					<a
						name="youzan"
						href="javascript:void(0)">
						{{ $t('template.youzan') }}
					</a>
				</Dropdown-item> -->
				<Dropdown-item name="cancel">
					<a
						name="logout"
						href="javascript:void(0)">
						{{ $t('template.cancel') }}
					</a>
				</Dropdown-item>

				<!-- <Dropdown-item name="revise">修改密码</Dropdown-item> -->
			</Dropdown-menu>
		</Dropdown>

		<!-- 语言切换 -->
		<!-- <Dropdown
			class="drop-down lang"
			trigger="click"
			placement="bottom-end"
			@on-click="confirmChangLang">

			<Button type="primary">
				<Icon type="ios-world-outline" /> {{ getCurrentLanguage }}
				<Icon type="arrow-down-b"/>
			</Button>

			<Dropdown-menu slot="list">
				<Dropdown-item
					v-for="(language, locale) in getLanguageOptions"
					:key="locale"
					:name="locale">{{ language }}</Dropdown-item>
			</Dropdown-menu>
		</Dropdown> -->

		<!--  修改密码模态框  -->
		<Modal
			v-model="show_form_modal"
			:title="$t('template.reset_password')"
			width="350"
			height="400">
			<Form
				ref="formValidate"
				:model="formValidate"
				:label-width="80"
				:rules="ruleValidate">
				<Form-item
					:label="$t('template.origin_password')"
					prop="old_password">
					<i-input
						v-model="formValidate.old_password"
						:placeholder="$t('template.please_enter_origin_password')"
						type="password"
						name="old_password"/>
				</Form-item>
				<Form-item
					:label="$t('template.new_password')"
					prop="new_password">
					<i-input
						v-model="formValidate.new_password"
						:placeholder="$t('template.please_enter_new_password')"
						type="password"
						name="new_password"/>
				</Form-item>
				<Form-item
					:label="$t('template.confirm_password')"
					prop="confirm_password">
					<i-input
						v-model="formValidate.confirm_password"
						:label="$t('template.confirm_password')"
						type="password"
						name="again_password"/>
				</Form-item>
				<Form-item>
					<Button
						type="primary"
						@click="handleSubmit('formValidate')">
						{{ $t('template.confirm') }}
					</Button>
				</Form-item>
			</Form>
			<div slot="footer"/>
		</Modal>
	</div>
</template>
<script>
import { mapGetters, mapMutations, mapActions } from 'vuex';
import API_LIST from 'src/API_LIST';

import {
	validatePass,
	validateNewPwd,
	validatePassCheck,
} from 'src/validate'; // 引入校验文件

const TOGGLE_SIDE_BAR = 'toggle-side-bar';

export default {

	props: {
		shrink: {
			type: Boolean,
			default() {
				return false;
			},
		},
	},

	data() {
		return {

			is_side_bar_open: true,

			notification_count: 0,

			timmer: null,

			show_form_modal: false,

			formValidate: { // 表单数据

				old_password: '',

				new_password: '',

				confirm_password: '',

			},
			// 表单校验规则
			ruleValidate: {
				old_password: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('template.origin_password') }),
						trigger: 'blur',
					},
					{ validator: validatePass, trigger: 'blur,change' },
				],
				new_password: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('template.new_password') }),
						trigger: 'blur',
					},
					{ validator: validateNewPwd, trigger: 'blur,change', pwd_info: this },
				],
				confirm_password: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('template.confirm_password') }),
						trigger: 'blur',
					},
					{ validator: validatePassCheck, trigger: 'blur,change', pwd_info: this },
				],
			},
		};
	},
	computed: {

		...mapGetters('menu', [
			'getSelectedMenu',
			'getMenus',
			'getUserType',
		]),

		...mapGetters('app', [
			'getCurrentLanguage',
			'getLanguageOptions',
		]),

		...mapGetters('userToken', [
			'getUserInfo',
			'getLoginPath',
		]),

		/**
         * 当前面包屑的展示
         * @return {Array} {面包屑所需数组}
         */
		currentBreadcrumb() {
			const self = this;

			// let home_route = '';

			// switch (this.getUserType) {
			// case 'panx':

			// 	home_route = '/admin/';

			// 	break;
			// case 'customer':

			// 	home_route = '/customer/';

			// 	break;

			// default:

			// 	home_route = '/store/';

			// 	break;
			// }

			const breadcrumb = [
				{
					// href: '/admin/device-management',
					name: this.$t('template.pandect'),
				},
			];

			const selected_menu = this.getSelectedMenu;

			const menus = this.getMenus;

			if (selected_menu === '/admin/' || selected_menu === '/mirror/') {
				self.setOpenSubmenu([]);

				return breadcrumb;
			}

			for (let i = 0; i < menus.length; i += 1) {
				const menu = menus[i];

				if (menu.name === selected_menu) {
					const new_crumb = {
						href: menu.name,
						name: menu.text,
					};

					breadcrumb.push(new_crumb);

					self.setOpenSubmenu([]);

					break;
				} else {
					const submenus = menu.submenus || [];

					for (let j = 0; j < submenus.length; j += 1) {
						const submenu = submenus[j];

						if (submenu.name === selected_menu) {
							const new_crumb = [
								{
									href: '',
									name: menu.text,
								},
								{
									href: submenu.name,
									name: submenu.text,
								},
							];

							breadcrumb.push(...new_crumb);

							self.setOpenSubmenu([menu.name]);

							break;
						}
					}
				}
			}

			return breadcrumb;
		},

	},

	methods: {

		...mapMutations('userToken', [
			'deleteToken',
		]),

		...mapActions('app', [
			'changeLocaleAction',
		]),

		...mapMutations('menu', [
			'clearCache',
			'setOpenSubmenu',
		]),

		...mapMutations('report', [
			'clearUserInfos',
		]),

		/**
         * 点击下拉菜单的事件
         * @param  {string} name {下拉菜单的name}
         * @return {undefined}
         */
		clickDropdown(name) {
			switch (name) {
			case 'cancel':
				this.cancelLogin();
				break;

			case 'revise':
				this.revisePassword();
				break;
			case 'edit-user-info':
				this.$emit('edit-user-info');
				break;
			case 'youzan':

				if (this.getUserType === 'store') {
					window.open(`${API_LIST.YOUZAN_AUTHORIZE}?store_id=${this.getUserInfo.store_id}`);
				} else {
					window.open(`${API_LIST.YOUZAN_AUTHORIZE}?customer_id=${this.getUserInfo.customer_id}`);
				}

				break;
			default:
				break;
			}
		},


		// /**
		//  * 根据语言的value显示语言的label
		//  * @param  {string} value {语言的value}
		//  * @return {undefined}
		//  */
		// showLang(value) {
		// 	const current_lang_object = this.langs.filter(lang => lang.value === value)[0];
		// 	this.current_lang = current_lang_object ? current_lang_object.label : '';
		// },

		/**
		 * 确认切换语言
		 * @param  {string} name {语言的lang}
		 * @return {undefined}
		 */
		confirmChangLang(language) {
			this.$Modal.confirm({
				// title: 'Title',
				content: `<p>${this.$t('template.switch_tip')}</p>`,
				onOk: () => {
					this.switchLocale(language);
				},
			});
		},

		/**
		 *  切换语言
		 * 	@param {String} language {语言}
		 *  @return {undefined}
		 */
		switchLocale(language) {
			// this.$Message.info(`${this.$t('template.current_language') + language}`);
			const type = this.getUserType;
			const { id } = this.getUserInfo;
			this.changeLocaleAction({ language, type, id });
			// window.location.reload();
		},

		/**
         * 退出登录
         * @return {undefined}
         */
		cancelLogin() {
			this.deleteToken();

			this.$Message.success(this.$t('template.logout_success'));

			this.clearCache();

			this.clearUserInfos();

			this.$router.push({
				path: this.getLoginPath,
			});
		},

		/**
         * 修改密码
         * @return {undefined}
         */
		revisePassword() {
			this.show_form_modal = true;
		},

		/**
         * 确定修改密码，提交表单
         * @param  {string} name {表单的ref}
         * @return {undefined}
         */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					// 提交
					this.confirmRevise();
				} else {
					this.$Message.error(this.$t('common.exist_empty_field'));
				}
			});
		},

		/**
         * 确定修改密码的post
         * @return {undefined}
         */
		confirmRevise() {
			this.$http.post(API_LIST.REVISE_PWD, this.formValidate)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.show_form_modal = false;

					this.$Message.success(this.$t('common.update_success'));

					this.$Message.info({
						content: this.$t('template.update_success_tip'), // '检测到您的密码已经更改，将在3秒后跳转到登录页面',
						duration: 3,
					});

					let counts = 3;

					const time = setInterval(() => {
						counts -= 1;

						if (counts === 0) {
							clearInterval(time);
							this.cancelLogin();
						}
					}, 3000);
				})
				.catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});
				});
		},

		/**
		 * 控制侧边导航栏收缩
		 * @return {undefined}
		 */
		toggleClick() {
			this.is_side_bar_open = !this.is_side_bar_open;
			this.$emit(TOGGLE_SIDE_BAR, this.is_side_bar_open);
		},

	},
};
</script>
